package com.tangx.search.service.impl;

import com.tangx.model.common.dtos.ResponseResult;
import com.tangx.model.common.enums.AppHttpCodeEnum;
import com.tangx.model.search.dtos.HistorySearchDto;
import com.tangx.search.pojos.ApUserSearch;
import com.tangx.search.service.ApUserSearchService;
import com.tangx.utils.common.SnowflakeIdWorker;
import com.tangx.utils.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步记录用户搜索关键词
     * @param keyword
     * @param userId
     */
    @Async("taskExecutor")
    @Override
    public void insert(String keyword, Integer userId) {


        if(StringUtils.isNotEmpty(keyword)){
            //1.查询搜索关键词记录
            ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword)), ApUserSearch.class);
            if(apUserSearch==null){
                SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0,0);
                //2.如果记录为空，直接保存
                apUserSearch = new ApUserSearch();
                apUserSearch.setId(String.valueOf(snowflakeIdWorker.nextId()));//雪花算法
                apUserSearch.setUserId(userId);//用户ID
                apUserSearch.setKeyword(keyword);//搜索关键词
                apUserSearch.setIsDeleted(0);//未删除
                apUserSearch.setCreatedTime(new Date());//创建或更新时间
                mongoTemplate.save(apUserSearch);
            } else {
                //3.如果数据不为空，根据状态处理

                //3.1 如果状态是未删除，更新时间即可
                if(apUserSearch.getIsDeleted()==0){
                    apUserSearch.setCreatedTime(new Date());
                    mongoTemplate.save(apUserSearch);
                } else {
                    //3.2 如果状态是已删除，更新为未删除同时更新时间
                    apUserSearch.setIsDeleted(0);
                    apUserSearch.setCreatedTime(new Date());
                    mongoTemplate.save(apUserSearch);
                }
            }
        }

    }

    @Override
    public ResponseResult findUserSearch() {
        Query query = Query.query(Criteria.where("userId").is(ThreadLocalUtil.getUserId()).and("isDeleted").is(0));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        query.limit(10);
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        ApUserSearch apUserSearch = mongoTemplate.findById(String.valueOf(dto.getId()), ApUserSearch.class);
        if(apUserSearch==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        apUserSearch.setIsDeleted(1);//已删除
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
